package com.swf.common.zip;

import java.io.*;
import java.util.*;
import java.util.regex.*;
import java.util.zip.*;

import com.swf.common.base.*;
import com.swf.common.filter.*;
import com.swf.common.io.*;
import com.swf.common.utils.*;

/**
 * description:操作Zip文件，读取zip文件内容
 * @version 1.0 2013-6-19
 * @author shenwf
 */
public class FwsZipUtils {
	Pattern pattern = Pattern.compile("/\\*[\\s\\d]*?\\*/");
	
	/**
	 * 从Zip文件中读取文件内容，默认读取java文件，字符编码为UTF-8
	 * @param file
	 * @return
	 * @throws ZipException
	 * @throws IOException
	 */
	public static Map<String, String> readZipFile(File file)
			throws ZipException, IOException {
		return readZipFile(file, null,null);
	}
	
	/**
	 * 从Zip文件中读取文件内容，默认读取java文件，字符编码为UTF-8
	 * @param file
	 * @param filter
	 * @return
	 * @throws ZipException
	 * @throws IOException
	 */
	public static Map<String, String> readZipFile(File file,FwsFilter filter)
			throws ZipException, IOException {
		return readZipFile(file, filter,null);
	}
	
	/**
	 * 从Zip文件中读取文件内容，默认读取java文件，字符编码为UTF-8
	 * @param file
	 * @param charst
	 * @return
	 * @throws ZipException
	 * @throws IOException
	 */
	public static Map<String, String> readZipFile(File file,String charst)
			throws ZipException, IOException {
		return readZipFile(file, null,charst);
	}
	
	/**
	 * 从Zip文件中读取文件内容，默认读取java文件，字符编码为系统默认字符集
	 * @param file 读取的zip文件
	 * @param filter 文件过滤器
	 * @param charset 字符集
	 * @return 返回包含文件的Map  key为zip文件名加文件名，value为文件的内容
	 * @throws ZipException
	 * @throws IOException
	 */
	public static Map<String, String> readZipFile(File file,
			FwsFilter filter,String charset) throws ZipException, IOException {
		Map<String, String> map = new HashMap<String, String>();
		ZipFile zfile = new ZipFile(file);
		String zfName = zfile.getName();
		zfName = zfName.substring(zfName
				.lastIndexOf(FwsConstants.file_separator) + 1);
		Enumeration<? extends ZipEntry> en = zfile.entries();
		ZipEntry entry;
		String key;
		String value;
		filter = (filter == null ? new FwsNameFilter() {
			@Override
			public boolean include(String name) {
				return name.endsWith(".java");
			}
		} : filter);
		charset = (charset==null?FwsCharset.defaultCharset:charset);
		while (en.hasMoreElements()) {
			entry = en.nextElement();
			if (!entry.isDirectory()) {
				key = zfName + ":" + entry.getName();
				if (!filter.accept(key))
					continue;
				value = FwsStringIOUtils.read(zfile.getInputStream(entry),
						charset);
				map.put(key, value);
			}
		}
		zfile.close();
		return map;
	}
	
	public static Collection<?> readZipContent(Map<?, ?> map){
		return map.values();
	}
	
	public static Collection<?> readZipFileName(Map<?, ?> map){
		return map.keySet();
	}
	
	public static String removeNotes(String text){
		return FwsPatternUtils.replaceRegex(text, "/\\*[\\s\\d]*?\\*/", "");
	}
	
}
